/*
  view-preload.js - BrowserView 预加载脚本
  让标签页内加载的网页也能使用受控的 window.electronAPI 接口
*/
const { contextBridge, ipcRenderer } = require('electron');

// Expose limited APIs to web content loaded in BrowserView
contextBridge.exposeInMainWorld('electronAPI', {
  // Tabs/state
  getTabsState: () => ipcRenderer.invoke('tabs:getState'),
  onTabsState: (callback) => {
    const listener = (_event, state) => callback(state);
    ipcRenderer.on('tabs:state', listener);
    return () => ipcRenderer.removeListener('tabs:state', listener);
  },

  // Navigation and tab actions
  createTab: (url) => ipcRenderer.send('tab:create', url),
  switchTab: (tabId) => ipcRenderer.send('tab:switch', tabId),
  closeTab: (tabId) => ipcRenderer.send('tab:close', tabId),
  reload: () => ipcRenderer.send('tab:reload'),
  goBack: () => ipcRenderer.send('tab:goBack'),
  goForward: () => ipcRenderer.send('tab:goForward'),
  navigate: (url) => ipcRenderer.send('tab:navigate', url),
  // Cookies APIs
  getCookies: () => ipcRenderer.invoke('tab:getCookies'),
  getCachedCookies: () => ipcRenderer.invoke('cookies:getCached'),
  getCachedCookiesFor: (urlOrOrigin) => ipcRenderer.invoke('cookies:getCachedFor', urlOrOrigin),
  setCachedCookiesFor: (urlOrOrigin, cookies) => ipcRenderer.invoke('cookies:setCachedFor', urlOrOrigin, cookies),
  getAllCachedCookies: () => ipcRenderer.invoke('cookies:getAllCached'),
  onCookiesUpdated: (callback) => {
    const listener = (_e, payload) => callback(payload);
    ipcRenderer.on('cookies:updated', listener);
    return () => ipcRenderer.removeListener('cookies:updated', listener);
  },
  hasAuthCookies: async () => {
    const list = await ipcRenderer.invoke('cookies:getCached');
    return Array.isArray(list) && list.length > 0;
  },
  hasAuthCookiesFor: async (urlOrOrigin) => {
    const list = await ipcRenderer.invoke('cookies:getCachedFor', urlOrOrigin);
    return Array.isArray(list) && list.length > 0;
  },
  getAuthCookies: async () => {
    try {
      const cached = await ipcRenderer.invoke('cookies:getCached');
      if (Array.isArray(cached) && cached.length > 0) return cached;
      const live = await ipcRenderer.invoke('tab:getCookies');
      if (Array.isArray(live) && live.length > 0) {
        await ipcRenderer.invoke('cookies:setCached', live);
      }
      return Array.isArray(live) ? live : [];
    } catch (_) {
      return [];
    }
  },
  getAuthCookiesFor: async (urlOrOrigin) => {
    try {
      const cached = await ipcRenderer.invoke('cookies:getCachedFor', urlOrOrigin);
      if (Array.isArray(cached) && cached.length > 0) return cached;
      // 仅当当前活动标签页属于该 origin 时，才尝试实时获取
      const state = await ipcRenderer.invoke('tabs:getState');
      const active = Array.isArray(state) ? state.find(t => t.isActive) : null;
      const currentUrl = active && active.url ? String(active.url) : '';
      const toOrigin = (() => { try { return new URL(String(urlOrOrigin)).origin.toLowerCase(); } catch { return String(urlOrOrigin || '').toLowerCase(); } })();
      const currentOrigin = (() => { try { return new URL(currentUrl).origin.toLowerCase(); } catch { return ''; } })();
      if (toOrigin && currentOrigin && toOrigin === currentOrigin) {
        const live = await ipcRenderer.invoke('tab:getCookies');
        if (Array.isArray(live) && live.length > 0) {
          await ipcRenderer.invoke('cookies:setCachedFor', urlOrOrigin, live);
          return live;
        }
      }
      return [];
    } catch (_) {
      return [];
    }
  },

  // UI sizing (optional)
  setTopUiHeight: (height) => ipcRenderer.send('ui:setTopHeight', height),

  // 网络请求API (解决跨域问题)
  fetch: async (url, options) => {
    const response = await ipcRenderer.invoke('network:fetch', url, options);
    
    // 创建一个类似fetch Response的对象，添加便捷方法
    return {
      ok: response.ok,
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      
      // 返回文本数据
      text: () => Promise.resolve(response.text),
      
      // 解析JSON数据
      json: () => {
        try {
          return Promise.resolve(JSON.parse(response.text));
        } catch (e) {
          return Promise.reject(new Error('Invalid JSON'));
        }
      },
      
      // 返回ArrayBuffer（用于二进制数据如图片、视频等）
      arrayBuffer: () => {
        try {
          const binaryString = atob(response.data);
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }
          return Promise.resolve(bytes.buffer);
        } catch (e) {
          return Promise.reject(new Error('Failed to decode binary data'));
        }
      },
      
      // 返回Blob（用于文件下载等）
      blob: () => {
        try {
          const binaryString = atob(response.data);
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }
          const contentType = response.headers['content-type'] || 'application/octet-stream';
          return Promise.resolve(new Blob([bytes], { type: contentType }));
        } catch (e) {
          return Promise.reject(new Error('Failed to create blob'));
        }
      }
    };
  },

  // 🍪 Cookie 管理
  clearServerCookies: () => ipcRenderer.invoke('clear-server-cookies'),
  
  // 获取当前页面的 cookies（调试用）
  getCurrentCookies: () => ipcRenderer.invoke('get-current-cookies'),

});

// 🎯 添加抖音发布器API
contextBridge.exposeInMainWorld('douyinAPI', {
  // 账号管理
  openLogin: () => ipcRenderer.invoke('douyin-open-login'),
  getCookies: () => ipcRenderer.invoke('douyin-get-cookies'),
  saveAccount: (accountData) => ipcRenderer.invoke('douyin-save-account', accountData),
  getAccounts: () => ipcRenderer.invoke('douyin-get-accounts'),
  getAccountById: (accountId) => ipcRenderer.invoke('douyin-get-account-by-id', accountId),
  deleteAccount: (accountId) => ipcRenderer.invoke('douyin-delete-account', accountId),
  updateAccount: (accountData) => ipcRenderer.invoke('douyin-update-account', accountData),
  updateAccountCookies: (updateData) => ipcRenderer.invoke('douyin-update-account-cookies', updateData),

  // 内容发布
  savePublishRecord: (recordData) => ipcRenderer.invoke('douyin-save-publish-record', recordData),
  startPublish: (contentData) => ipcRenderer.invoke('douyin-open-publish', contentData),
  updatePublishStatus: (recordId, statusData) => ipcRenderer.invoke('douyin-update-publish-record-status', recordId, statusData),
  getPublishRecords: () => ipcRenderer.invoke('douyin-get-publish-records'),

  // 🆕 新增的查询方法
  getPublishRecordsByAccountId: (accountId) => ipcRenderer.invoke('douyin-get-publish-records-by-account-id', accountId),
  getPublishRecordById: (recordId) => ipcRenderer.invoke('douyin-get-publish-record-by-id', recordId),

  // 🆕 Cookie验证
  validateAccountCookies: (accountId) => ipcRenderer.invoke('douyin-validate-account-cookies', accountId),
 
  // 事件监听
  onPublishStatusUpdate: (callback) => {
    ipcRenderer.on('publish-status-update', (event, data) => callback(data));
  }
});

// 🎯 添加小红书发布器API
contextBridge.exposeInMainWorld('xiaohongshuAPI', {
  // 账号管理
  openLogin: () => ipcRenderer.invoke('xiaohongshu-open-login'),
  getCookies: () => ipcRenderer.invoke('xiaohongshu-get-cookies'),
  saveAccount: (accountData) => ipcRenderer.invoke('xiaohongshu-save-account', accountData),
  getAccounts: () => ipcRenderer.invoke('xiaohongshu-get-accounts'),
  getAccountByAccountId: (accountId) => ipcRenderer.invoke('xiaohongshu-get-account-by-account-id', accountId),
  deleteAccountByAccountId: (accountId) => ipcRenderer.invoke('xiaohongshu-delete-account-by-account-id', accountId),
  
  // 🆕 Cookie验证功能
  validateAccountCookies: (accountId) => ipcRenderer.invoke('xiaohongshu-validate-account-cookies', accountId),

  // 内容发布
  savePublishRecord: (recordData) => ipcRenderer.invoke('xiaohongshu-save-publish-record', recordData),
  startPublish: (contentData) => ipcRenderer.invoke('xiaohongshu-open-publish', contentData),
  updatePublishStatus: (recordId, statusData) => ipcRenderer.invoke('xiaohongshu-update-publish-record-status', recordId, statusData),
  getPublishRecords: () => ipcRenderer.invoke('xiaohongshu-get-publish-records'),
  closePublishWindow: () => ipcRenderer.invoke('xiaohongshu-close-publish-window'),

  // 🆕 新增的查询方法
  getPublishRecordsByAccountId: (accountId) => ipcRenderer.invoke('xiaohongshu-get-publish-records-by-account-id', accountId),
  getPublishRecordById: (recordId) => ipcRenderer.invoke('xiaohongshu-get-publish-record-by-id', recordId),
 
  // 事件监听
  onPublishStatusUpdate: (callback) => {
    ipcRenderer.on('xiaohongshu-publish-status-update', (event, data) => callback(data));
  },

  // 🆕 移除事件监听器
  removePublishStatusListener: () => {
    ipcRenderer.removeAllListeners('xiaohongshu-publish-status-update');
  }
});
